<template>
  <div class="formItem">
    <DefineEvalItem v-slot="{ item, showItem }">
      <div
        class="pgpf"
        :class="{ 'pgpf-complete': showItem.isComplete }"
        @click="handleEval(item)"
      >
        {{ showItem.text }}
      </div>
    </DefineEvalItem>
    <div
      v-for="(item, index) in forms"
      :key="index"
      style="display: flex; flex-wrap: wrap; align-items: center"
    >
      <template
        v-if="
          item.dictValue === 'yx-pgpf' ||
          item.dictValue === 'vte_braden' ||
          item.dictValue === 'vte_dd'
        "
      >
        <ReuseEvalItem :item="item" :showItem="getEvalShowItem(item)" />
      </template>
      <template
        v-else-if="
          item.dictValue === 'yx-crl-in' || item.dictValue === 'yx-crl-out'
        "
      >
        <div
          v-for="(item2, index2) in io[item.dictValue]"
          :key="index2"
          class="ioItem"
        >
          <el-select
            :value="item2.itemCode"
            :style="'width:' + multipleFormWidth + 'px;margin-right: 10px'"
            placeholder="请选择"
            @change="e => valueChange(e, item, index2, 'itemCode')"
          >
            <el-option
              v-for="item in item.enumArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            v-if="item.dictValue === 'yx-crl-in'"
            :value="item2.medication"
            :style="'width:' + singleFormWidth + 'px;margin-right: 10px'"
            @input="e => valueChange(e, item, index2, 'medication')"
          />
          <el-input
            :value="item2.value"
            :style="'width:' + multipleFormWidth + 'px;margin-right: 10px'"
            @input="e => valueChange(e, item, index2, 'value')"
          >
            <template #suffix>ml</template>
          </el-input>
          <Select
            v-if="item.dictValue === 'yx-crl-out'"
            v-model="item2.nature"
            :style="'width:' + multipleFormWidth + 'px'"
            :dict="item2.itemCode"
            filterable
          />
          <div
            class="removeBtn"
            @click="toRemoveCrlItem(item.dictValue, index2)"
          >
            -
          </div>
        </div>
        <div class="addBtn" @click="toAddCrlItem(item.dictValue)">+</div>
      </template>
      <template v-else-if="item.itemCode === 'care_remark'">
        <div class="full-block" @click="showTempDialog(item)">
          {{ getValue(item) }}
        </div>
      </template>
      <template v-else-if="item.dictValue === 'yx-hlcz'">
        <el-autocomplete
          :value="getValue(item)"
          :style="
            'width:' +
            (forms.length > 1 ? multipleFormWidth : singleFormWidth) +
            'px'
          "
          :fetch-suggestions="
            (queryString, cb) => querySearchAsync(queryString, cb, item.enumArr)
          "
          @input="e => valueChange(e, item)"
        ></el-autocomplete>
      </template>
      <template v-else-if="item.obsvDataType === 'enum'">
        <el-select
          :value="getValue(item)"
          :style="
            'width:' +
            (forms.length > 1 ? multipleFormWidth : singleFormWidth) +
            'px'
          "
          placeholder="请选择"
          @change="e => valueChange(e, item)"
        >
          <el-option
            v-for="item in item.enumArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </template>
      <template v-else>
        <el-input
          :value="getValue(item)"
          :style="
            'width:' +
            (forms.length > 1 ? multipleFormWidth : singleFormWidth) +
            'px'
          "
          @input="e => valueChange(e, item)"
        >
          <template #suffix>{{ unit }}</template>
        </el-input>
      </template>
    </div>
  </div>
</template>

<script lang="ts">
import { createReusableTemplate } from '@vueuse/core'
import {
  computed,
  defineComponent,
  onBeforeUnmount,
  onMounted,
  reactive,
  toRefs,
  watch
} from 'vue'

import Select from '@/components/MyComp/Select.vue'
import { getBusFromInstance, getStoreFromInstance } from '@/utils/instance'
const [DefineEvalItem, ReuseEvalItem] = createReusableTemplate()

export default defineComponent({
  name: 'FormItem',
  components: {
    DefineEvalItem,
    ReuseEvalItem,
    Select
  },
  props: {
    childNode: {
      type: Array,
      default: () => []
    },
    unit: {
      type: String,
      default: ''
    },
    evalItems: {
      type: Object,
      default: () => ({})
    },
    gcx: {
      type: Object,
      default: () => ({})
    },
    hlcz: {
      type: Object,
      default: () => ({})
    },
    io: {
      type: Object,
      default: () => ({})
    },
    pfTime: {
      type: String,
      default: ''
    }
  },
  emits: [
    'value-change',
    'eval',
    'eval-fall',
    'eval-braden',
    'to-add-crl-item',
    'to-remove-crl-item'
  ],
  setup(props, { emit }) {
    const state = reactive({
      forms: [],
      multipleFormWidth: 110,
      singleFormWidth: 180,
      evalShowItems: []
    })

    const bus = getBusFromInstance()
    const store = getStoreFromInstance()

    const patCur = computed(() => store.getters.patCur)

    const getValue = computed(() => item => {
      if (item.dictValue === 'yx-gcx' && props.gcx[item.obsvCode]) {
        return props.gcx[item.obsvCode].value
      } else if (item.dictValue === 'yx-hlcz' && props.hlcz[item.itemCode]) {
        return props.hlcz[item.itemCode].value
      }
      return ''
    })

    function valueChange(e, item, crlIndex = '', crlKey = '') {
      emit('value-change', {
        value: e,
        item: item,
        crlIndex,
        crlKey
      })
    }

    function handleEval(item) {
      if (item.dictValue === 'yx-pgpf') {
        emit('eval', {
          activePgCode: item.pgType,
          activePgId: item.pgId
        })
      } else if (item.dictValue === 'vte_dd') {
        emit('eval-fall')
      } else if (item.dictValue === 'vte_braden') {
        emit('eval-braden')
      }
    }

    /**
     * 获取评估评分显示项
     */
    function getEvalShowItem(item) {
      let text = item.title
      let isComplete = false
      let val

      if (item.dictValue === 'yx-pgpf') {
        // 处理类似疼痛评估有多个Tab的情况
        if (item.pgType) {
          if (item.pgType == props.evalItems[item.pgId].activePgType) {
            val = props.evalItems[item.pgId].val
          }
        } else {
          val = props.evalItems[item.pgId].val
        }
      } else if (
        item.dictValue === 'vte_dd' ||
        item.dictValue === 'vte_braden'
      ) {
        val = props.evalItems[item.dictValue].val
      }

      if (val !== null && val !== undefined) {
        val = String(val)
        text += ` ${val || '+'}`
        isComplete = val ? true : false
      } else {
        text += ' +'
      }

      return {
        text,
        isComplete
      }
    }

    function toAddCrlItem(dictValue) {
      emit('to-add-crl-item', dictValue)
    }

    function toRemoveCrlItem(dictValue, index) {
      emit('to-remove-crl-item', {
        dictValue,
        index
      })
    }

    function querySearchAsync(queryString, cb, restaurants) {
      const results = queryString
        ? restaurants.filter(createStateFilter(queryString))
        : restaurants

      cb(results)
    }

    function createStateFilter(queryString) {
      return state => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
      }
    }

    // 打开护理记录
    function showTempDialog(item) {
      bus.$emit('NursingRecords/openDialog', {
        flag: 'intensiveCare',
        para: {
          id: props.hlcz[item.itemCode]?.id || 0,
          itemName: props.hlcz[item.itemCode]?.itemName || '备注',
          mappedTime: +new Date(props.pfTime),
          patientIdent: patCur.value.patientIdent,
          hospitalNumber: patCur.value.hospitalNumber,
          recordTime: new Date(props.pfTime),
          careContent: props.hlcz[item.itemCode]?.value || ''
        },
        type: '1',
        title: '备注'
      })
    }

    watch(
      () => props.childNode,
      val => {
        if (val) {
          const childNodeClone = JSON.parse(JSON.stringify(val))
          state.forms = childNodeClone.map(item => {
            if (item.enumMap) {
              const enumMap = JSON.parse(item.enumMap)
              const enumArr = []
              if (
                item.dictValue === 'yx-crl-in' ||
                item.dictValue === 'yx-crl-out'
              ) {
                const allowItemCodesIn = ['in_bsl', 'in_kf', 'in_qt']
                enumMap.forEach(item2 => {
                  if (
                    (item.dictValue === 'yx-crl-in' &&
                      allowItemCodesIn.includes(item2.itemCode)) ||
                    item.dictValue === 'yx-crl-out'
                  ) {
                    enumArr.push({
                      label: item2.itemName,
                      value: item2.itemCode
                    })
                  }
                })
              } else if (item.dictValue === 'yx-hlcz') {
                enumMap.list.forEach(item2 => {
                  enumArr.push({
                    label: item2.itemName,
                    value: item2.itemName
                  })
                })
                item.obsvDataType = enumMap.itemValueType
              } else {
                for (const key in enumMap) {
                  enumArr.push({
                    label: enumMap[key],
                    value: key
                  })
                }
              }
              item.enumArr = enumArr
            }
            return item
          })
        }
      },
      {
        immediate: true,
        deep: true
      }
    )

    onMounted(() => {
      const item = props.childNode?.find(v => v.itemCode === 'care_remark')
      if (item) {
        bus.$on('NursingRecords/refreshNursing', data => {
          valueChange(data, item)
        })
      }
    })
    onBeforeUnmount(() => {
      bus.$off('NursingRecords/refreshNursing')
    })

    return {
      ...toRefs(state),
      getValue,
      valueChange,
      handleEval,
      getEvalShowItem,
      toAddCrlItem,
      toRemoveCrlItem,
      querySearchAsync,
      showTempDialog
    }
  }
})
</script>

<style scoped lang="scss">
.formItem {
  display: flex;
  align-items: center;

  & > div {
    margin-left: 10px;

    &:first-child {
      margin-left: 0;
    }
  }

  .pgpf {
    padding: 0 14px;
    min-width: 88px;
    height: 30px;
    background: #0e5fd8;
    font-size: 14px;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }

  .pgpf-complete {
    background: #fcfcfc;
    border: 1px solid #dfe4ed;
    color: #333;
  }

  .ioItem {
    margin-right: 30px;
    margin-bottom: 10px;
  }

  .addBtn {
    width: 24px;
    height: 24px;
    background: #0e5fd8;
    border-radius: 2px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 10px;
    color: #fff;
    cursor: pointer;
    margin-bottom: 10px;
  }

  .removeBtn {
    width: 18px;
    height: 18px;
    background: #f66;
    border-radius: 50%;
    display: inline-block;
    text-align: center;
    line-height: 18px;
    font-size: 10px;
    color: #fff;
    cursor: pointer;
    margin-bottom: 10px;
    margin-left: 10px;
  }

  .full-block {
    min-width: 200px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    color: #606266;
    padding: 0 15px;
    min-height: 32px;
    line-height: 32px;
  }
}
</style>
